package com.v.im.authservice.customImpl;

import com.v.im.businessapi.dto.resultDTO.ImUserResultDTO;
import com.v.im.businessapi.feign.ImUserClientService;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

@Service
public class UserServiceDetail implements UserDetailsService {

    @Resource
    private ImUserClientService imUserClientService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        ImUserResultDTO imUserResultDTO = imUserClientService.getImUserByUserName(username);
        if (imUserResultDTO == null || StringUtils.isBlank(imUserResultDTO.getName())) {
            throw new UsernameNotFoundException("用户:" + username + ",不存在!");
        }
        Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
        boolean enabled = true; // 可用性 :true:可用 false:不可用
        boolean accountNonExpired = true; // 过期性 :true:没过期 false:过期
        boolean credentialsNonExpired = true; // 有效性 :true:凭证有效 false:凭证无效
        boolean accountNonLocked = true; // 锁定性 :true:未锁定 false:已锁定
        return new User(imUserResultDTO.getName(), imUserResultDTO.getPassword(),
                enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, grantedAuthorities);
    }
}
